# pylint: disable-msg=E1101
"""
@author: Sergiy Tsymbalyuk
"""

import logging

from pylons import request, tmpl_context as c, url
from pylons.i18n import lazy_ugettext as _
from pylons.controllers.util import redirect, abort
from pylons.decorators import jsonify

from repoze.what.plugins.pylonshq import ControllerProtector
from repoze.what.predicates import Any, in_group

from sqlalchemy import join

from chowa.lib.site.forms import TabularFieldSet
from chowa.lib.site.navigation import Tab
from chowa.model.organization import Division
from hrms.lib.base import BaseController, render, Session
from hrms.model.person import Employee

log = logging.getLogger(__name__)

@ControllerProtector(Any(in_group('hrms.hr'), in_group('hrms.administrators')))
class ProfileController(BaseController):
    __secondary_tabs__ = [
        [
            Tab(params=dict(action='index'), caption=_('View')),
            Tab(params=dict(action='edit'), caption=_('Edit')),
        ]
    ]
    
    
    def __before__(self, id):
        c.employee = Session.query(Employee).get(id)
        identity = request.environ.get('repoze.who.identity')
        if not in_group('hrms.administrators').is_met(request.environ):
            user = identity['user']
            user_employee = Session.query(Employee).get(user.person_id)
            if user_employee.division.district_id <> c.employee.division.district_id:
                return abort(403)
    
    def index(self, id):
        if c.employee.is_employee:
            c.district_url = url(controller='org/district',
                               action='employees',
                               id=c.employee.division.district.id)
            return render('/hrms/profile/employee.html')
        else:
            return render('/hrms/profile/former.html')
    
    def edit(self, id):
        fs = TabularFieldSet(c.employee)
        if request.method == 'POST':
            fs.configure(include=[fs.surname,
                                  fs.name,
                                  fs.patronymic,
                                  fs.born,
                                  fs.gender,
                                  fs.iin,
                                  fs.internal_phone,
                                  fs.local_phone,
                                  fs.mobile_phone,
                                  fs.voip_phone,
                                  fs.email_address,
                                  fs.division,
                                  fs.position,
                                  fs.office,
                                  fs.is_employee,
                                  fs.is_insider])
            fs.rebind(data=request.POST)
            if fs.validate():
                fs.sync()
                Session.commit()
                return redirect(url.current(action='index'))
        fs.configure(include=[fs.surname,
                              fs.name,
                              fs.patronymic,
                              fs.born,
                              fs.gender,
                              fs.iin])
        c.person_form = fs.render()
        
        fs.configure(include=[fs.internal_phone,
                              fs.local_phone,
                              fs.mobile_phone,
                              fs.voip_phone])
        c.phones_form = fs.render()
        
        fs.configure(include=[fs.email_address])
        c.email_form = fs.render()
        
        fs.configure(include=[fs.division,
                              fs.position,
                              fs.office,
                              fs.is_employee,
                              fs.is_insider])
        
        if c.employee.division_id:
            filter_record = Session.query(Division).get(c.employee.division_id)
            filter_fs = TabularFieldSet(filter_record)
        else:
            filter_record = Division()
            filter_fs = TabularFieldSet(filter_record, Session)
        fs.engine.filters['division_id'] = filter_fs.district
        
        c.form = fs.render()
        return render('/hrms/profile/edit.html')
    
    @jsonify
    def get_ids(self, id):
        query = Session.query(Division).filter_by(district_id=id)
        return [record.id for record in query]
